package com.ckfinder.connector.handlers.command;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.IOFileUploadException;
import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.ckfinder.connector.configuration.Constants;
import com.ckfinder.connector.configuration.Events.EventTypes;
import com.ckfinder.connector.configuration.IConfiguration;
import com.ckfinder.connector.data.AfterFileUploadEventArgs;
import com.ckfinder.connector.errors.ConnectorException;
import com.ckfinder.connector.errors.ErrorUtils;
import com.ckfinder.connector.utils.AccessControlUtil;
import com.ckfinder.connector.utils.FileUtils;
import com.ckfinder.connector.utils.ImageUtils;
public class FileUploadCommand extends Command implements IPostCommand {
    protected String ckEditorFuncNum;
    private String langCode;
    protected boolean uploaded;
    protected int errorCode;
    private static final char[] UNSAFE_FILE_NAME_CHARS = {':', '*', '?', '|', '/'};
    public FileUploadCommand() {
        this.errorCode = 0;
        this.fileName = "";
        this.newFileName = "";
        this.type = "";
        this.uploaded = false;
    }
    @Override
    public void execute(final OutputStream out) throws ConnectorException {
        if (configuration.isDebugMode() && this.exception != null) {
            throw new ConnectorException(this.errorCode, this.exception);
        }
        try {
            StringerrorMsg=(this.errorCode==0)?"":ErrorUtils.getInstance().getErrorMsgByLangAnd             Code(this.langCode,this.errorCode, this.configuration);
            errorMsg = errorMsg.replaceAll("%1", this.newFileName);
            String path = "";
            if (!uploaded) {
                this.newFileName = "";
                this.currentFolder = "";
            } else {
                path = configuration.getTypes().get(type).getUrl()
                        + this.currentFolder;
            }
            if (this.responseType != null && this.responseType.equals("txt")) {
                out.write((this.newFileName + "|" + errorMsg).getBytes("UTF-8"));
            } else {
                out.write("<script type=\"text/javascript\">".getBytes("UTF-8"));
                if (checkFuncNum()) {
                    handleOnUploadCompleteCallFuncResponse(out, errorMsg, path);
                } else {
                    handleOnUploadCompleteResponse(out, errorMsg);
                }
                out.write("</script>".getBytes("UTF-8"));
            }
        } catch (IOException e) {
            throw new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED, e);
        }
    }
    protected boolean checkFuncNum() {
        return this.ckFinderFuncNum != null;
    }
    protected void handleOnUploadCompleteCallFuncResponse(final OutputStream out,
                                                          final String errorMsg,
                                                          final String path)
            throws IOException {
        this.ckFinderFuncNum = this.ckFinderFuncNum.replaceAll(
                "[^\\d]", "");
        out.write(("window.parent.CKFinder.tools.callFunction("
                + this.ckFinderFuncNum + ", '"
                + path
                + FileUtils.backupWithBackSlash(this.newFileName, "'")
                + "', '" + errorMsg + "');").getBytes("UTF-8"));
    }
    protected void handleOnUploadCompleteResponse(final OutputStream out,
                                                  final String errorMsg) throws IOException {
        out.write("window.parent.OnUploadCompleted(".getBytes("UTF-8"));
        out.write(("\'" + FileUtils.backupWithBackSlash(this.newFileName, "'") + "\'").getBytes("UTF-8"));
        out.write((",\'"+(this.errorCode!=Constants.Errors.CKFINDER_CONNECTOR_ERROR_NONE ? errorMsg
                : "") + "\'").getBytes("UTF-8"));
        out.write(");".getBytes("UTF-8"));
    }
    @Override
    public void initParams(final HttpServletRequest request,
                           final IConfiguration configuration, final Object... params)
            throws ConnectorException {
        super.initParams(request, configuration, params);
        this.ckFinderFuncNum = request.getParameter("CKFinderFuncNum");
        this.ckEditorFuncNum = request.getParameter("CKEditorFuncNum");
        this.responseType = request.getParameter("response_type");
        this.langCode = request.getParameter("langCode");
        if (this.errorCode == Constants.Errors.CKFINDER_CONNECTOR_ERROR_NONE) {
            this.uploaded = uploadFile(request);
        }
    }
    private boolean uploadFile(final HttpServletRequest request) {
        if (!AccessControlUtil.getInstance(configuration).checkFolderACL(
                this.type, this.currentFolder, this.userRole,
                AccessControlUtil.CKFINDER_CONNECTOR_ACL_FILE_UPLOAD)) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED;
            return false;
        }
        return fileUpload(request);
    }
    @SuppressWarnings("unchecked")
    private boolean fileUpload(final HttpServletRequest request) {
        try {
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload uploadHandler = new ServletFileUpload(
                    fileItemFactory);
            List<FileItem> items = uploadHandler.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    String path = configuration.getTypes().get(this.type).getPath()
                            + this.currentFolder;
                    this.fileName = getFileItemName(item);
                    try {
                        if (validateUploadItem(item, path)) {
                            return saveTemporaryFile(path, item);
                        }
                    } finally {
                        item.delete();
                    }
                }
            }
            return false;
        } catch (InvalidContentTypeException e) {
            if (configuration.isDebugMode()) {
                this.exception = e;
            }
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT;
            return false;
        } catch (IOFileUploadException e) {
            if (configuration.isDebugMode()) {
                this.exception = e;
            }
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
            return false;
        } catch (SizeLimitExceededException e) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
            return false;
        } catch (FileSizeLimitExceededException e) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
            return false;
        } catch (ConnectorException e) {
            this.errorCode = e.getErrorCode();
            return false;
        } catch (Exception e) {
            if (configuration.isDebugMode()) {
                this.exception = e;
            }
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
            return false;
        }
    }
    private boolean saveTemporaryFile(final String path, final FileItem item)
            throws Exception {
        File file = new File(path, this.newFileName);
        AfterFileUploadEventArgs args = new AfterFileUploadEventArgs();
        args.setCurrentFolder(this.currentFolder);
        args.setFile(file);
        args.setFileContent(item.get());
        if (!ImageUtils.isImage(file)) {
            item.write(file);
            if (configuration.getEvents() != null) {
                configuration.getEvents().run(EventTypes.AfterFileUpload,args, configuration);
            }
            return true;
        } else if (ImageUtils.checkImageSize(
                item.getInputStream(), this.configuration)) {
            ImageUtils.createTmpThumb(item.getInputStream(), file,
                    getFileItemName(item), this.configuration);
            if (configuration.getEvents() != null) {
                configuration.getEvents().run(EventTypes.AfterFileUpload,
                        args, configuration);
            }
            return true;
        } else if (configuration.checkSizeAfterScaling()) {
            ImageUtils.createTmpThumb(item.getInputStream(), file,
                    getFileItemName(item), this.configuration);
            if (FileUtils.checkFileSize(configuration.getTypes().get(this.type), file.length())) {
                if (configuration.getEvents() != null) {
                    configuration.getEvents().run(EventTypes.AfterFileUpload,
                            args, configuration);
                }
                return true;
            } else {
                file.delete();
                this.errorCode =
                        Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
                return false;
            }
        }
        //should be unreacheable
        return false;
    }
    private String getFinalFileName(final String path, final String name) {
        File file = new File(path, name);
        int number = 0;
        String nameWithoutExtension = FileUtils.getFileNameWithoutExtension(name, false);
        Pattern p = Pattern.compile("^(AUX|COM\\d|CLOCK\\$|CON|NUL|PRN|LPT\\d)$", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(nameWithoutExtension);
        boolean protectedName = m.find() ? true : false;
        while (true) {
            if (file.exists() || protectedName) {
                number++;
                StringBuilder sb = new StringBuilder();
                sb.append(FileUtils.getFileNameWithoutExtension(name, false));
                sb.append("(" + number + ").");
                sb.append(FileUtils.getFileExtension(name, false));
                this.newFileName = sb.toString();
                file = new File(path, this.newFileName);			this.errorCode=Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_FILE_RENAMED;
                protectedName = false;
            } else {
                return this.newFileName;
            }
        }
    }
    private boolean validateUploadItem(final FileItem item, final String path) {
        if (item.getName() != null && item.getName().length() > 0) {
            this.fileName = getFileItemName(item);
        } else {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_INVALID;
            return false;
        }
        this.newFileName = this.fileName;
        for (char c : UNSAFE_FILE_NAME_CHARS) {
            this.newFileName = this.newFileName.replace(c, '_');
        }
        if (configuration.isDisallowUnsafeCharacters()) {
            this.newFileName = this.newFileName.replace(';', '_');
        }
        if (configuration.forceASCII()) {
            this.newFileName = FileUtils.convertToASCII(this.newFileName);
        }
        if (!this.newFileName.equals(this.fileName)) {
            this.errorCode=Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_INVALID_NAME_RENAMED;
        }
        if (FileUtils.checkIfDirIsHidden(this.currentFolder, configuration)) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST;
            return false;
        }
        if (!FileUtils.checkFileName(this.newFileName)
                || FileUtils.checkIfFileIsHidden(this.newFileName,
                configuration)) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_NAME;
            return false;
        }
        int checkFileExt = FileUtils.checkFileExtension(this.newFileName,
                configuration.getTypes().get(type));
        if (checkFileExt == 1) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION;
            return false;
        }
        if (configuration.ckeckDoubleFileExtensions()) {
            this.newFileName = FileUtils.renameFileWithBadExt(configuration.getTypes().get(type), this.newFileName);
        }
        try {
            File file = new File(path, getFinalFileName(path, this.newFileName));
            if (!FileUtils.checkFileSize(configuration.getTypes().get(this.type),
                    item.getSize())
                    && !(configuration.checkSizeAfterScaling() && ImageUtils.isImage(file))) {
                this.errorCode =
                        Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
                return false;
            }
            if (configuration.getSecureImageUploads() && ImageUtils.isImage(file)
                    && !ImageUtils.checkImageFile(item)) {
                this.errorCode =
                        Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT;
                return false;
            }
            if (!FileUtils.checkIfFileIsHtmlFile(file.getName(), configuration)
                    && FileUtils.detectHtml(item)) {
                this.errorCode =						Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_WRONG_HTML_FILE;
                return false;
            }
        } catch (SecurityException e) {
            if (configuration.isDebugMode()) {
                this.exception = e;
            }
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
            return false;
        } catch (IOException e) {
            if (configuration.isDebugMode()) {
                this.exception = e;
            }
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
            return false;
        }
        return true;
    }
    @Override
    public void setResponseHeader(final HttpServletResponse response,
                                  final ServletContext sc) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
    }
    private String getFileItemName(final FileItem item) {
        Pattern p = Pattern.compile("[^\\\\/]+$");
        Matcher m = p.matcher(item.getName());
        return (m.find()) ? m.group(0) : "";
    }
    protected boolean checkParam(final String reqParam)
            throws ConnectorException {
        if (reqParam == null || reqParam.equals("")) {
            return true;
        }
        if (Pattern.compile(Constants.INVALID_PATH_REGEX).matcher(reqParam).find()) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_NAME;
            return false;
        }
        return true;
    }
    @Override
    protected boolean checkHidden()
            throws ConnectorException {
        if (FileUtils.checkIfDirIsHidden(this.currentFolder, configuration)) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST;
            return true;
        }
        return false;
    }
    @Override
    protected boolean checkConnector(final HttpServletRequest request)
            throws ConnectorException {
        if (!configuration.enabled() || !configuration.checkAuthentication(request)) {
            this.errorCode =
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_CONNECTOR_DISABLED;
            return false;
        }
        return true;
    }
    @Override
    protected boolean checkIfCurrFolderExists(final HttpServletRequest request)
            throws ConnectorException {
        String tmpType = getParameter(request, "type");
        File currDir = new File(configuration.getTypes().get(tmpType).getPath()
                + this.currentFolder);
        if (currDir.exists() && currDir.isDirectory()) {
            return true;
        } else {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_FOLDER_NOT_FOUND;
            return false;
        }
    }
}
package com.ckfinder.connector.handlers.command;
        import java.io.File;
        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.List;
        import javax.servlet.http.HttpServletRequest;
        import org.w3c.dom.Element;
        import com.ckfinder.connector.configuration.Constants;
        import com.ckfinder.connector.configuration.IConfiguration;
        import com.ckfinder.connector.data.XmlAttribute;
        import com.ckfinder.connector.data.XmlElementData;
        import com.ckfinder.connector.errors.ConnectorException;
        import com.ckfinder.connector.utils.AccessControlUtil;
        import com.ckfinder.connector.utils.FileUtils;
        import com.ckfinder.connector.utils.ImageUtils;
        import com.ckfinder.connector.utils.NaturalOrderComparator;
public class GetFilesCommand extends XMLCommand {
    private static final float BYTES = 1024f;
    private List<String> files;
    private String fullCurrentPath;
    private String showThumbs;
    @Override
    public void initParams(final HttpServletRequest request,
                           final IConfiguration configuration, final Object... params)
            throws ConnectorException {
        super.initParams(request, configuration);
        this.showThumbs = request.getParameter("showThumbs");
    }
    @Override
    protected void createXMLChildNodes(final int errorNum, final Element rootElement)
            throws ConnectorException {
        if (errorNum == Constants.Errors.CKFINDER_CONNECTOR_ERROR_NONE) {
            createFilesData(rootElement);
        }
    }
    protected int getDataForXml() {
        this.fullCurrentPath = configuration.getTypes().get(this.type).getPath()
                + this.currentFolder;
        if (!AccessControlUtil.getInstance(configuration).checkFolderACL(
                this.type, this.currentFolder, this.userRole,
                AccessControlUtil.CKFINDER_CONNECTOR_ACL_FILE_VIEW)) {
            return Constants.Errors.CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED;
        }
        File dir = new File(this.fullCurrentPath);
        try {
            if (!dir.exists()) {
                return Constants.Errors.CKFINDER_CONNECTOR_ERROR_FOLDER_NOT_FOUND;
            }
            files = FileUtils.findChildrensList(dir, false);
        } catch (SecurityException e) {
            if (configuration.isDebugMode()) {
                throw e;
            } else {
                return Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
            }
        }
        filterListByHiddenAndNotAllowed();
        Collections.sort(files, new NaturalOrderComparator());
        return Constants.Errors.CKFINDER_CONNECTOR_ERROR_NONE;
    }
    private void filterListByHiddenAndNotAllowed() {
        List<String> tmpFiles = new ArrayList<String>();
        for(Stringfile:this.files){if(FileUtils.checkFileExtension(file,this.configuration.getTypes().get(this.type))== 0
                && !FileUtils.checkIfFileIsHidden(file, this.configuration)) {
            tmpFiles.add(file);
        }
        }
        this.files.clear();
        this.files.addAll(tmpFiles);
    }
    private void createFilesData(final Element rootElement) {
        Element element = creator.getDocument().createElement("Files");
        for (String filePath : files) {
            File file = new File(this.fullCurrentPath, filePath);
            if (file.exists()) {
                XmlElementData elementData = new XmlElementData("File");
                XmlAttribute attribute = new XmlAttribute("name", filePath);
                elementData.getAttributes().add(attribute);
                attribute = new XmlAttribute("date",
                        FileUtils.parseLastModifDate(file));
                elementData.getAttributes().add(attribute);
                attribute = new XmlAttribute("size", getSize(file));
                elementData.getAttributes().add(attribute);
                if (ImageUtils.isImage(file) && isAddThumbsAttr()) {
                    String attr = createThumbAttr(file);
                    if (!attr.equals("")) {
                        attribute = new XmlAttribute("thumb", attr);
                        elementData.getAttributes().add(attribute);
                    }
                }
                elementData.addToDocument(this.creator.getDocument(), element);
            }
        }
        rootElement.appendChild(element);
    }
    private String createThumbAttr(final File file) {
        File thumbFile = new File(configuration.getThumbsPath()
                + File.separator + type + this.currentFolder,
                file.getName());
        if (thumbFile.exists()) {
            return file.getName();
        } else if (isShowThumbs()) {
            return "?".concat(file.getName());
        }
        return "";
    }
    private String getSize(final File file) {
        if (file.length() > 0 && file.length() < BYTES) {
            return "1";
        } else {
            return String.valueOf(Math.round(file.length() / BYTES));
        }
    }
    private boolean isAddThumbsAttr() {
        return configuration.getThumbsEnabled()
                && (configuration.getThumbsDirectAccess()
                || isShowThumbs());
    }
    private boolean isShowThumbs() {
        return (this.showThumbs != null && this.showThumbs.toString().equals("1"));
    }
}
package demo;
        import java.awt.*;
        import java.awt.geom.Ellipse2D;
        import javax.swing.ImageIcon;
        import javax.swing.JPanel;
        import org.jfree.chart.*;
        import org.jfree.chart.axis.NumberAxis;
        import org.jfree.chart.plot.CategoryPlot;
        import org.jfree.chart.plot.PlotOrientation;
        import org.jfree.chart.renderer.category.LineAndShapeRenderer;
        import org.jfree.chart.title.TextTitle;
        import org.jfree.data.category.CategoryDataset;
        import org.jfree.data.category.DefaultCategoryDataset;
        import org.jfree.ui.*;
public class LineChartDemo1 extends ApplicationFrame
{
    public LineChartDemo1(String s)
    {
        super(s);
        JPanel jpanel = createDemoPanel();
        jpanel.setPreferredSize(new Dimension(500, 270));
        setContentPane(jpanel);
    }
    private static CategoryDataset createDataset()
    {
        DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
        defaultcategorydataset.addValue(212D, "Classes", "JDK 1.0");
        defaultcategorydataset.addValue(504D, "Classes", "JDK 1.1");
        defaultcategorydataset.addValue(1520D, "Classes", "JDK 1.2");
        defaultcategorydataset.addValue(1842D, "Classes", "JDK 1.3");
        defaultcategorydataset.addValue(2991D, "Classes", "JDK 1.4");
        defaultcategorydataset.addValue(3500D, "Classes", "JDK 1.5");
        return defaultcategorydataset;
    }
    private static JFreeChart createChart(CategoryDataset categorydataset)
    {
        JFreeChart jfreechart = ChartFactory.createLineChart("Java Standard Class Library", null, "Class Count", categorydataset, PlotOrientation.VERTICAL, false, true, false);
        jfreechart.addSubtitle(new TextTitle("Number of Classes By Release"));
        TextTitle texttitle = new TextTitle("Source: Java In A Nutshell (5th Edition) by David Flanagan (O'Reilly)");
        texttitle.setFont(new Font("SansSerif", 0, 10));
        texttitle.setPosition(RectangleEdge.BOTTOM);
        texttitle.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        jfreechart.addSubtitle(texttitle);
        jfreechart.setBackgroundPaint(Color.white);
        CategoryPlot categoryplot = (CategoryPlot)jfreechart.getPlot();
        categoryplot.setBackgroundPaint(Color.lightGray);
        categoryplot.setRangeGridlinePaint(Color.gray);
        categoryplot.setRangeGridlinesVisible(false);
        java.net.URL url = (demo.LineChartDemo1.class).getClassLoader().getResource("OnBridge11small.png");
        if(url != null)
        {
            ImageIcon imageicon = new ImageIcon(url);
            categoryplot.setBackgroundImage(imageicon.getImage());
        }
        categoryplot.setBackgroundImageAlpha(1.0F);
        NumberAxis numberaxis = (NumberAxis)categoryplot.getRangeAxis();
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer)categoryplot.getRenderer();
        lineandshaperenderer.setShapesVisible(true);
        lineandshaperenderer.setDrawOutlines(true);
        lineandshaperenderer.setUseFillPaint(true);
        lineandshaperenderer.setFillPaint(Color.white);
        lineandshaperenderer.setSeriesStroke(0, new BasicStroke(3F));
        lineandshaperenderer.setSeriesOutlineStroke(0, new BasicStroke(2.0F));
        lineandshaperenderer.setSeriesShape(0, new java.awt.geom.Ellipse2D.Double(-5D, -5D, 10D, 10D));
        return jfreechart;
    }
    public static JPanel createDemoPanel()
    {
        JFreeChart jfreechart = createChart(createDataset());
        return new ChartPanel(jfreechart);
    }
    public static void main(String args[])
    {
        LineChartDemo1 linechartdemo1 = new LineChartDemo1("JFreeChart - Line Chart Demo 1");
        linechartdemo1.pack();
        RefineryUtilities.centerFrameOnScreen(linechartdemo1);
        linechartdemo1.setVisible(true);
    }
}
    private void createConnectorData(final Element rootElement) {
        // connector info
        Element element = creator.getDocument().createElement("ConnectorInfo");
        element.setAttribute("enabled", String.valueOf(configuration.enabled()));
        element.setAttribute("s", getLicenseName());
        element.setAttribute("c",
                createLicenseKey(configuration.getLicenseKey()));
        element.setAttribute("thumbsEnabled", String.valueOf(
                configuration.getThumbsEnabled()));
        element.setAttribute("uploadCheckImages", configuration.checkSizeAfterScaling() ? "false" : "true");
        if (configuration.getThumbsEnabled()) {
            element.setAttribute("thumbsUrl", configuration.getThumbsURL());
            element.setAttribute("thumbsDirectAccess", String.valueOf(
                    configuration.getThumbsDirectAccess()));
            element.setAttribute("thumbsWidth", String.valueOf(configuration.getMaxThumbWidth()));
            element.setAttribute("thumbsHeight", String.valueOf(configuration.getMaxThumbHeight()));
        }
        element.setAttribute("imgWidth", String.valueOf(configuration.getImgWidth()));
        element.setAttribute("imgHeight", String.valueOf(configuration.getImgHeight()));
        if (configuration.getPlugins().size() > 0) {
            element.setAttribute("plugins", getPlugins());
        }
        rootElement.appendChild(element);
    }
    private String getPlugins() {
        StringBuffer sb = new StringBuffer();
        boolean first = false;
        for (PluginInfo item : configuration.getPlugins()) {
            if (item.isEnabled()) {
                if (first) {
                    sb.append(",");
                }
                sb.append(item.getName());
                first = true;
            }
        }
        return sb.toString();
    }
    private String getLicenseName() {
        if (validateLicenseKey(configuration.getLicenseKey())) {
            int index = Constants.CKFINDER_CHARS.indexOf(configuration.getLicenseKey().charAt(0))
                    % LICENSE_CHAR_NR;
            if (index == 1 || index == 4) {
                return configuration.getLicenseName();
            }
        }
        return "";
    }
    private String createLicenseKey(final String licenseKey) {
        if (validateLicenseKey(licenseKey)) {
            StringBuilder sb = new StringBuilder();
            for (int i : LICENSE_CHARS) {
                sb.append(licenseKey.charAt(i));
            }
            return sb.toString();
        }
        return "";
    }
    private boolean validateLicenseKey(final String licenseKey) {
        return licenseKey != null && licenseKey.length() == LICENSE_KEY_LENGTH;
    }
    public void createPluginsData(final Element rootElement) throws ConnectorException {
        Element element = creator.getDocument().createElement("PluginsInfo");
        rootElement.appendChild(element);
        InitCommandEventArgs args = new InitCommandEventArgs();
        args.setXml(this.creator);
        args.setRootElement(rootElement);
        if (configuration.getEvents() != null) {
            configuration.getEvents().run(EventTypes.InitCommand, args, configuration);
        }
    }
    private void createResouceTypesData(final Element rootElement) throws Exception {
        //resurcetypes
        Element element = creator.getDocument().createElement("ResourceTypes");
        rootElement.appendChild(element);
        List<String> types = null;
        if (super.type != null && !super.type.equals("")) {
            types = new ArrayList<String>();
            types.add(super.type);
        } else {
            types = getTypes();
        }
        for (String key : types) {
            ResourceType resourceType = configuration.getTypes().get(key);
            if (((this.type == null || this.type.equals(key)) && resourceType != null)&& AccessControlUtil.getInstance(this.configuration).checkFolderACL(key,"/",this.userRole,
                    AccessControlUtil.CKFINDER_CONNECTOR_ACL_FOLDER_VIEW)) {
                Element childElement = creator.getDocument().
                        createElement("ResourceType");
                childElement.setAttribute("name", resourceType.getName());
                childElement.setAttribute("acl", String.valueOf(
                        AccessControlUtil.getInstance(configuration).checkACLForRole(key,"/",this.userRole)));
                childElement.setAttribute("hash", randomHash(
                        resourceType.getPath()));
                childElement.setAttribute(
                        "allowedExtensions",
                        resourceType.getAllowedExtensions());
                childElement.setAttribute(
                        "deniedExtensions",
                        resourceType.getDeniedExtensions());
                childElement.setAttribute("url", resourceType.getUrl() + "/");
                Long maxSize = resourceType.getMaxSize();
                childElement.setAttribute("maxSize", (maxSize != null && maxSize > 0)  maxSize.toString() : "0");
                childElement.setAttribute("hasChildren",					FileUtils.hasChildren("/",newFile(PathUtils.escape(resourceType.getPath())),
                        configuration, resourceType.getName(), this.userRole).toString());
                element.appendChild(childElement);
            }
        }
    }
    private List<String> getTypes() {
        if (configuration.getDefaultResourceTypes().size() > 0) {
            return configuration.getDefaultResourceTypes();
        } else {
            return configuration.getResourceTypesOrder();
        }
    }
    private String randomHash(final String folder) throws Exception {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            try {
                algorithm.update(folder.getBytes("UTF8"));
            } catch (UnsupportedEncodingException e) {
                if (configuration.isDebugMode()) {
                    throw e;
                }
                algorithm.update(folder.getBytes());
            }
            byte[] messageDigest = algorithm.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                hexString.append(Integer.toHexString(HASH & messageDigest[i]));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            if (configuration.isDebugMode()) {
                throw e;
            }
            return "";
        }
    }